package com.jingyi.framework.security.provider;

import com.jingyi.framework.security.token.WxAuthenticationToken;
import com.jingyi.framework.web.service.WxUserDetailServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 微信登录校验逻辑
 */
@Component
public class WxAuthenticationProvider implements AuthenticationProvider {
    private static final Logger logger = LoggerFactory.getLogger(WxAuthenticationProvider.class);

    @Autowired
    private WxUserDetailServiceImpl wxUserDetailService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String openId = authentication.getName();
        UserDetails user;

        try{
            user = wxUserDetailService.loadUserByUsername(openId);
        }catch (UsernameNotFoundException var6) {
            logger.debug("Failed to find User " + openId);
            throw new BadCredentialsException("WxAuthenticationProvider.badCredentials");
        }

        if (authentication.getCredentials() == null) {
            logger.debug("Failed to authenticate since no credentials provided");
            throw new BadCredentialsException("WxAuthenticationProvider.badCredentials");
        } else {
            String presentedPassword = authentication.getCredentials().toString();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (!passwordEncoder.matches(presentedPassword, user.getPassword())) {
                logger.debug("Failed to authenticate since password does not match stored value");
                throw new BadCredentialsException("WxAuthenticationProvider.badCredentials");
            }
        }

        WxAuthenticationToken token = new WxAuthenticationToken(user,authentication.getCredentials(),authentication.getAuthorities());
        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WxAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
